package edu.gatech.cs4400.spring2014.A8.model;

import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * Class extended by any queries seeking to get data from the database.
 * Following a successful connection to the database, the class will
 * pass the ResultSet to the parseResult method that must be implemented
 * by the reader.
 * 
 * @author Stephen
 *
 */
public abstract class ReadQuery extends Query {
	
	/**
	 * Attempt to read from the database using the command in the sql variable.
	 * If the read is successful, pass the data to the parseResult method.
	 * Track flags about the success/failure/execution of the query
	 */
	protected boolean execute() {
		boolean result = false;
		if (!executed) {
			try {
				ResultSet rs = ConnectionManager.statement.executeQuery(sql);
				parseResult(rs);
				result = true;
			}
			catch (SQLException e) {
				failed = true;
				System.out.printf("SQL Exception: ", e.getMessage());
				System.out.printf(e.getLocalizedMessage());
			}
			executed = true;
		}
		else {
			System.out.println("Already executed this query.");
		}
		return result;
	}
	
	/**
	 * Default constructor. Sets flags to false.
	 */
	protected ReadQuery() {
		executed = false;
		failed = false;
		sql = "";
	}
	
	/**
	 * Interpret the results of the query.
	 * @param rs
	 * @throws SQLException
	 */
	protected abstract void parseResult(ResultSet rs) throws SQLException;
}
